import { useRequest } from "ahooks";
import { message, Modal } from "antd"
import { useEffect, useRef, useState } from "react";
import { create_embedding, update_embedding } from "../../../api/request";
import 'cherry-markdown/dist/cherry-markdown.css';
import Cherry from 'cherry-markdown';

interface ExamineProps {
    id: number;
    markdown: string;
    open: boolean;
    type: 'create' | 'update';
    onChange: (open: boolean) => void;
    onOk: (open: boolean) => void;
    documentId?: number;
}

/**
 * markdown渲染组件
 */
export default (props: ExamineProps) => {
    const { markdown, open, onChange, id, onOk, type, documentId } = props
    const [markdownData, setMarkdownData] = useState(markdown)
    const { loading: updateLoading, run: updateRun } = useRequest(update_embedding, {
        manual: true,
        onSuccess: (result) => {
            if (result.code == 200) {
                message.success('修改成功')
                onOk(false)
            } else {
                message.success('修改失败')
            }
        }
    })
    const { loading: createLoading, run: createRun } = useRequest(create_embedding, {
        manual: true,
        onSuccess: (result) => {
            if (result.code == 200) {
                message.success('新建成功')
                onOk(false)
            } else {
                message.success('新建失败')
            }
        }
    })
    const [createId, setCreateId] = useState<number>()
    const cherryRef = useRef<Cherry>()

    useEffect(() => {
        if (open) {
            setMarkdownData(markdown)
            if (!cherryRef.current) {
                cherryRef.current = new Cherry({
                    id: 'markdown-container',
                    value: markdownData,
                    toolbars: {
                        // 定义顶部工具栏
                        toolbar: [
                            'undo', 'redo', '|',
                            // 把字体样式类按钮都放在加粗按钮下面
                            { bold: ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'ruby'] },
                            'color', 'size', '|', 'header', 'list', 'panel', '|',
                            // 把插入类按钮都放在插入按钮下面
                            { insert: ['image', 'audio', 'video', 'link', 'hr', 'br', 'code', 'formula', 'toc', 'table', 'drawIo'] },
                            'graph'
                        ],
                        // 定义侧边栏，默认为空
                        sidebar: ['theme', 'mobilePreview', 'copy'],
                        // 定义顶部右侧工具栏，默认为空
                        toolbarRight: ['fullScreen', 'export'],
                        // 定义选中文字时弹出的“悬浮工具栏”，默认为 ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'quote', '|', 'size', 'color']
                        bubble: ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'ruby', '|', 'color', 'size',],
                        // 定义光标出现在行首位置时出现的“提示工具栏”，默认为 ['h1', 'h2', 'h3', '|', 'checklist', 'quote', 'table', 'code']
                        float: ['table', 'code', 'graph'],
                        toc: {
                            updateLocationHash: false, // 要不要更新URL的hash
                            defaultModel: 'pure', // pure: 精简模式/缩略模式，只有一排小点； full: 完整模式，会展示所有标题
                            showAutoNumber: false, // 是否显示自增序号
                            position: 'absolute', // 悬浮目录的悬浮方式。当滚动条在cherry内部时，用absolute；当滚动条在cherry外部时，用fixed
                        },
                    }
                });
            }
            if (type == 'update') {
                cherryRef.current.setValue(markdownData || "")
            } else {
                cherryRef.current.setValue('')
            }
            if (documentId) {
                setCreateId(documentId)
            }
        }
    }, [open, markdownData])


    return <Modal
        open={open}
        title={type == 'create' ? "创建" : "编辑"}
        width={1200}
        confirmLoading={type == 'create' ? createLoading : updateLoading}
        onOk={() => {
            if (type == 'create') {
                if (createId)
                    createRun({
                        id: createId,
                        document: [cherryRef.current?.getValue()] as string[]
                    })
                else
                    message.error('请选择文档')
            }
            else {
                updateRun({
                    id,
                    document: cherryRef.current?.getValue() as string
                })
            }
        }}
        onClose={() => onChange(false)}
        onCancel={() => onChange(false)}>
       {/* {!documentId &&  <CustomSelect value={createId} placeholder="请选择文档" onChange={(id: number) => setCreateId(id)} className="w-[200px]" />} */}
        <div className="overflow-auto h-[600px] mt-2">
            <div id="markdown-container" className="rounded-lg overflow-hidden" style={{ height: '100%', border: '1px solid #ECEDEE' }} ></div>
        </div>
    </Modal>
}

